/**
 * 项目名称: Topic_108.cpp
 * 项目路径: study/DataStructure/LeetCode/树/简单
 * 编辑时间: 2024年08月21日08时17分06秒
 * 用   户: 轻尘
 */

#include <bits/stdc++.h>

using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;

    TreeNode() : val(0), left(nullptr), right(nullptr) {}

    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}

    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    /**
     * 平衡二叉排序树构建:
     *  每次总是选择中间位置左边的数字作为根节点
     * @param nums
     * @return
     */
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        return helper(nums,0,nums.size()-1);
    }

    TreeNode* helper(vector<int>&nums,int left,int right){
        if(left>right)return nullptr;
        //总是选择中间左边位置的数字作为根节点
        int mid = (left + right)/2;
        TreeNode* root = new TreeNode(nums[mid]);
        root->left = helper(nums,left,mid-1);
        root->right = helper(nums,mid+1,right);
        return root;
    }
};
